package cn.wenlihelp.controller.power;

import cn.wenlihelp.bean.Appeal;
import cn.wenlihelp.model.Result;
import cn.wenlihelp.service.AppealService;
import com.github.pagehelper.PageInfo;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;

@RestController
@RequestMapping("/appeal")
public class AppealController {

    private int errorCodeRoot = 20000;

    private String model = "appeal";
    private String modelPath = "power/" + model;


    @Resource
    private AppealService appealService;

    @RequestMapping
    public ModelAndView home() {
        return new ModelAndView(modelPath + "/index");
    }

    @GetMapping("/add")
    public ModelAndView addPage() {
        return new ModelAndView(modelPath + "/add");
    }

    @GetMapping("/{id}")
    public ModelAndView updatePage(@PathVariable("id") Long id, ModelMap modelMap) {
        Appeal appeal = appealService.findById(id);
        modelMap.addAttribute(model, appeal);
        return new ModelAndView(modelPath + "/update");
    }

    //region 查询账号
    @GetMapping(produces = "application/json")
    public Object findAll(Appeal appeal,
                          @RequestParam(defaultValue = "1") int page,
                          @RequestParam(defaultValue = "10") int limit) {
        PageInfo<Appeal> pageInfo = appealService.findAll(page, limit, appeal);
        return Result.success(pageInfo.getTotal(), pageInfo.getList());
    }
    //endregion

    //region 批量删除账号
    @DeleteMapping
    public Result deleteByIds(@RequestParam("ids[]") Integer[] ids) {

        if (appealService.deleteByIds(ids)) {
            return Result.success("删除成功");
        } else {
            return new Result().setCode(errorCodeRoot + 1).setMsg("删除失败");
        }
    }
    //endregion

    //region 新增账号
    @PutMapping
    public Result add(@RequestBody Appeal appeal) {
        if (appealService.insert(appeal)) {
            return Result.success("新增成功");
        } else {
            return new Result().setCode(errorCodeRoot + 2).setMsg("新增失败");
        }
    }
    //endregion


    //region 修改账号
    @PostMapping
    public Result updataAppeal(@RequestBody Appeal appeal) {
        if (appealService.updateByPrimaryKey(appeal)) {
            return Result.success("修改成功");
        } else {
            return new Result().setCode(errorCodeRoot + 3).setMsg("新增失败");
        }
    }
    //endregion


}
